package com;

import com.dto.AdvertiseDTO;
import com.service.IndexService;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.JacksonObjectMapperFactoryBean;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: nkrivko
 * Date: 26.12.13
 * Time: 15:31
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class IndexController {

    private ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private IndexService service;

    @RequestMapping("/index")
    public ModelAndView index() {
        return new ModelAndView("/index.jsp");
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public AdvertiseDTO add(@Valid AdvertiseDTO dto, BindingResult validatedResult) {
        if (validatedResult.hasErrors()) {
        }
        return new AdvertiseDTO();
    }

    @RequestMapping("/search")
    @ResponseBody
    public String search() {
        try {
            AdvertiseDTO advertiseDTO = service.search();
            String result = mapper.writeValueAsString(advertiseDTO);
            return result;
        } catch (IOException e) {
            return e.getMessage();
        }
    }

}
